package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"kukukaki/models"
	"kukukaki/util"
	"strconv"
	"time"
	 "strings"
)

type IngredientController struct {
	beego.Controller
}
type iiresult struct {
	Result int    `json:"r"`
	Err    string `json:"err"`
	Msg    string `json:"msg"`
}

//字典更新
func (c *IngredientController) UII() {
	var key string = c.GetString("key")
	r := iiresult{}
	if key == "spark" {
		util.UpdateDict()

	} else {
		r = iiresult{Err: "error"}
	}
	c.Data["json"] = &r
	c.ServeJSON()
	return

}

//中文去掉空格
func (c *IngredientController) SetNameCN() {
	var key string = c.GetString("key")
	r := iiresult{}

	if key == "spark" {
		count := models.GetIiData2()
		  fmt.Printf("--count---", count)
	 

		for _, v := range models.IiData2 { //循环遍历整个数组(仅输出元素)
			 
			cn := strings.Replace(v.Name, " ", "", -1) //去空格
			cn = strings.ToUpper(cn)  //转大写
			ii ,err :=models.AddNameCn(&v.ID,&cn)
		    if ii == 0 {
		    	fmt.Printf("e======= "+err.Error())
		    }else{
		    	fmt.Printf("OK======= ",cn)
		    }

	        
	    }
		fmt.Printf("--------ok-------")
		r = iiresult{Result: 1}		
	} else {
		r = iiresult{Err: "error"}
	}
	c.Data["json"] = &r
	c.ServeJSON()
	return

}

//获取数量
func (c *IngredientController) InitData() {
	var key string = c.GetString("key")
	r := iiresult{}
	if key == "spark" {
		count := models.GetIiData("")
		r = iiresult{Result: count}
	} else {
		r = iiresult{Err: "error"}
	}
	c.Data["json"] = &r
	c.ServeJSON()
	return
}

//索引ID 查内容
func (c *IngredientController) DataItem() {
	var key string = c.GetString("key")
	var strindex string = c.GetString("index")
	r := iiresult{}
	if key == "spark" && strindex != "" {
		index, err1 := strconv.Atoi(strindex)  //转int
		if err1 != nil {
			r = iiresult{Err: err1.Error()}
			c.Data["json"] = &r
		} else {
			
			if models.IiData == nil {
				r = iiresult{Err: "IiData is  null"}
				c.Data["json"] = &r
			} else {
				ii := models.IiData[index]
				c.Data["json"] = &ii
			}
		}

	} else {
		r = iiresult{Err: "error"}
		c.Data["json"] = &r
	}
	
	c.ServeJSON()
	return
}

//添加
func (c *IngredientController) AddII() {
	var key string = c.GetString("key")
	var data string = c.GetString("data")
	fmt.Println("-data-", data)
	r := iiresult{}
	if key == "spark" {
		if data != "" {
			ii := models.IngredientInfo{}

			json.Unmarshal([]byte(data), &ii)
			ii.RegTime = time.Now().Format("2006-01-02 15:04:05")
			rr, err := models.UpsertIdII(&ii)
			if err != nil {
				r = iiresult{Err: err.Error()}
			} else {
				if rr >= 0 {
					r = iiresult{Result: 1}

				}
			}
		} else {
			r = iiresult{Err: "data is null"}
		}

	} else {
		r = iiresult{Err: "error"}
	}
	c.Data["json"] = &r
	c.ServeJSON()
	return

}
